package services

import (
	"errors"
	"fmt"
	"hft/Database/admin"
	"hft/Http/Models/dao"
	utils "hft/Http/Utils"
	"hft/global"
	"hft/tools"
	"regexp"
)

type FriendlyLink struct{}

func (*FriendlyLink) Create(data *admin.FriendlyLink, claims tools.BaseClaims) (err error) {

	var region *admin.Region

	var account *admin.Account

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	err = global.OC_DB.Where("manage_id = ?", account.ID).First(&region).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	data.RegionLink = fmt.Sprintf("%v%v,", region.Link, region.ID)
	data.City = int(region.ID)

	err = global.OC_DB.Create(&data).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*FriendlyLink) Edit(data *admin.FriendlyLink, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	var nowLink *admin.FriendlyLink

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	err = global.OC_DB.First(&nowLink, data.ID).Error

	if err != nil {
		return errors.New("找不到该友情链接")
	}

	match, _ := regexp.MatchString(fmt.Sprintf("^(%v)", account.RegionLink), nowLink.RegionLink)

	if !match {
		return errors.New("你无权修改该友情链接")
	}

	err = global.OC_DB.Model(&admin.FriendlyLink{}).Where("id = ?", data.ID).Updates(map[string]interface{}{
		"name": data.Name,
		"link": data.Link,
		"sort": data.Sort,
	}).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	return nil
}

func (*FriendlyLink) List(claims tools.BaseClaims) (list []*admin.FriendlyLink, err error) {

	var account *admin.Account

	var links []*admin.FriendlyLink

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return nil, errors.New("未知错误500")
	}

	global.OC_DB.Where("region_link LIKE ?", fmt.Sprintf("%v%%", account.RegionLink)).Find(&links)

	return links, nil

}

func (*FriendlyLink) Delete(ids []int, claims tools.BaseClaims) (err error) {

	var account *admin.Account

	var links []*admin.FriendlyLink

	err = global.OC_DB.Scopes(dao.ParseAccountDao.Parse(claims, global.OC_DB)).First(&account).Error

	if err != nil {
		return errors.New("未知错误500")
	}

	err = global.OC_DB.Find(&links, ids).Error

	if !utils.IsAllLinksBelongThisRegion(links, account.RegionLink) {
		return errors.New("你无权修改该链接")
	}

	global.OC_DB.Unscoped().Delete(&links)

	return nil

}

var FriendlyLinkService = new(FriendlyLink)
